#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QStandardItemModel>
#include <QTableView>
#include <QDebug>

class JsonDataFetcher : public QObject
{
    Q_OBJECT

public:
    JsonDataFetcher() : networkManager(new QNetworkAccessManager)
    {
        connect(networkManager, &QNetworkAccessManager::finished, this, &JsonDataFetcher::onNetworkReply);
        fetchDataFromServer();
    }

private slots:
    void onNetworkReply(QNetworkReply *reply)
    {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();

            // 解析 JSON 数据
            QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
            QJsonObject jsonObj = jsonDoc.object();
            QJsonArray booksArray = jsonObj.value("books").toArray();

            // 创建一个数据模型
            QStandardItemModel model;
            model.setColumnCount(3);
            model.setHorizontalHeaderLabels(QStringList() << "Author" << "Title" << "Price");

            // 将解析后的数据添加到数据模型中
            for (int i = 0; i < booksArray.size(); ++i) {
                QJsonObject book = booksArray[i].toObject();
                QString author = book.value("author").toString();
                QString title = book.value("title").toString();
                double price = book.value("price").toDouble();

                QList<QStandardItem *> rowItems;
                rowItems << new QStandardItem(author) << new QStandardItem(title) << new QStandardItem(QString::number(price));
                model.appendRow(rowItems);
            }

            // 创建一个 TableView 并设置数据模型
            QTableView tableView;
            tableView.setModel(&model);
            tableView.resize(400, 300);
            tableView.show();
        } else {
            qDebug() << "Network request failed:" << reply->errorString();
        }

        reply->deleteLater();
        QCoreApplication::quit();  // 仅用于示例，实际中可以根据需求决定是否退出应用程序
    }

private:
    void fetchDataFromServer()
    {
        QUrl url("http://127.0.0.1:5000/textbooks");
        QNetworkRequest request(url);
        networkManager->get(request);
    }

    QNetworkAccessManager *networkManager;
};

//#include "main.moc"
